package com.bluexmicro.ota2.ui.screen.config

import android.graphics.Color
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.bluexmicro.ota2.R
import com.bluexmicro.ota2.picker.device.LaunchDevicePicker
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.LineData
import com.google.accompanist.flowlayout.FlowRow

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ConfigScreen(navController: NavController) {

    val context = LocalContext.current
    val viewModel = viewModel<ConfigViewModel>()

    val devicePicker = rememberLauncherForActivityResult(
        contract = LaunchDevicePicker(),
        onResult = {
            if (it != null) {
                viewModel.tryConnect(context, it.device.address)
            }
        }
    )

    val ready = viewModel.ready.collectAsState()

    var index by remember {
        mutableStateOf(0)
    }
    var currentValue by remember {
        mutableStateOf(0f)
    }


    val data = viewModel.lineData.collectAsState()
    Scaffold(
        topBar = {
            Column {
                CenterAlignedTopAppBar(
                    title = {
                        Text(text = "Config")
                    },
                    actions = {
                        Button(onClick = {
                            viewModel.save(context = context)
                        }) {
                            Text(text = "Save")
                        }
                    },
                    navigationIcon = {
                        Button(onClick = {
                            devicePicker.launch(Unit)
                        }) {

                            Text(text = if (ready.value) "Connected" else "Connect")
                        }
                    }
                )
                Divider(thickness = Dp.Hairline)
            }

        }
    ) {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(it),
            contentPadding = PaddingValues(16.dp)
        ) {

            item {
                Column(
                    modifier = Modifier
                        .background(MaterialTheme.colorScheme.background)
                        .fillMaxWidth()
                        .aspectRatio(1.25f)
                ) {
                    ComposableLineChart(lineData = data.value)
                }
            }

            item {
                FlowRow {
                    for (i in 0..29) {
                        FilterChip(
                            selected = index == i,
                            onClick = {
                                index = i
                                currentValue = viewModel.src[i]
                            },
                            label = {
//                                val v = displays.value[i]
                                val indexStr = (i + 1).toString().padStart(2, '0')
                                Text(text = "${indexStr}")
                            }
                        )
                    }
                }
            }
            item {
                ConfigItem(onValueUpdated = { newValue ->
                    viewModel.setValue(index, newValue)
                })
            }

        }
    }

}

@Composable
fun ComposableLineChart(lineData: LineData) {
    AndroidView(
        factory = { context ->
            LineChart(context).apply {
                // 设置图表数据
                data = lineData
                // 去掉网格线
                axisLeft.setDrawGridLines(false)
                xAxis.setDrawGridLines(false)

                // 禁止缩放
                setScaleEnabled(false)
                setPinchZoom(false)


                // 隐藏右边的 Y 轴值
                axisRight.isEnabled = true
                axisLeft.isEnabled = false

                xAxis.position = XAxis.XAxisPosition.BOTTOM

                xAxis.setLabelCount(5, true)
                axisRight.axisMaximum = 40f
                axisRight.axisMinimum = 0f
                axisRight.textColor = Color.GRAY
                xAxis.textColor = Color.GRAY
                description.text = ""
                isScaleYEnabled = false
                axisRight.granularity = 10f // 设置网格线的间隔为 10
                // 刷新图表
                invalidate()
                // 其他图表配置...
            }
        },
        update = {
            // 如果有新数据，可以在这里更新图表
            it.data = lineData
            it.invalidate()
        },
        modifier = Modifier.fillMaxSize()
    )
}


@Composable
fun ConfigItem(initValue: Float = 0f, onValueUpdated: (newValue: Float) -> Unit) {
    var value by remember {
        mutableStateOf(initValue)
    }
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically
    ) {
        FilledIconButton(
            onClick = {
                val tmp = value - 1
                if (tmp in 0f..40f) {
                    value = tmp
                }
                onValueUpdated.invoke(value)
            },
            colors = IconButtonDefaults.filledIconButtonColors(
                containerColor = androidx.compose.ui.graphics.Color.LightGray,
                contentColor = androidx.compose.ui.graphics.Color.Black
            ),
            shape = RoundedCornerShape(2.dp),
            modifier = Modifier.size(32.dp)
        ) {
            Icon(
                painter = painterResource(id = R.drawable.ic_reduce),
                contentDescription = ""
            )
        }

        Slider(
            value = value,
            valueRange = 0f..40f,
            steps = 41,
            onValueChange = {
                value = it
                onValueUpdated.invoke(value)
            },
            modifier = Modifier.weight(1f)
        )

        FilledIconButton(
            onClick = {
                val tmp = value + 1
                if (tmp in 0f..40f) {
                    value = tmp
                }
                onValueUpdated.invoke(value)
            },
            colors = IconButtonDefaults.filledIconButtonColors(
                containerColor = androidx.compose.ui.graphics.Color.LightGray,
                contentColor = androidx.compose.ui.graphics.Color.Black
            ),
            shape = RoundedCornerShape(2.dp),
            modifier = Modifier.size(32.dp)
        ) {
            Icon(
                painter = painterResource(id = R.drawable.ic_add),
                contentDescription = ""
            )
        }
    }
}